package com.huaxin.common.tools;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

/**
 * Created by hebing on 2016/3/18.
 * 基础工具类
 */
public class Util {
    /*****************************************
     * Gson
     ******************************************/
    private static final Gson mGson = new Gson();

    public static Gson gson() {
        return mGson;
    }

    /*****************************************
     * SharedPreferences
     ******************************************/
    private static final String PREF_NAME = "hxcould";

    public static void put(Context context, String key, Object val) {
        SharedPreferences.Editor editor = context.getSharedPreferences(PREF_NAME, 0).edit();
        if (val instanceof Integer) editor.putInt(key, (Integer) val);
        else if (val instanceof Boolean) editor.putBoolean(key, (Boolean) val);
        else if (val instanceof Float) editor.putFloat(key, (Float) val);
        else if (val instanceof Long) editor.putLong(key, (Long) val);
        else if (val instanceof String) editor.putString(key, (String) val);
        else if (val instanceof Set) {
            try {
                Set<String> vals = (Set<String>) val;
                editor.putStringSet(key, vals);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        editor.apply();
    }

    public static Object get(Context context, String key, Object def) {
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, 0);

        if (def instanceof Integer) return preferences.getInt(key, (Integer) def);
        if (def instanceof Boolean) return preferences.getBoolean(key, (Boolean) def);
        if (def instanceof Float) return preferences.getFloat(key, (Float) def);
        if (def instanceof Long) return preferences.getLong(key, (Long) def);
        if (def instanceof String) return preferences.getString(key, (String) def);
        if (def instanceof Set) {
            try {
                Set<String> vals = (Set<String>) def;
                return preferences.getStringSet(key, vals);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return preferences.getAll().get(key);
    }

    private static HashMap<String, String> headers;
    private final static HashMap<String, ArrayList<Callback>> downloading = new HashMap<>();

    public interface Callback {
        void onSuccess();

        void onError(String error);

        void onProgress(int percent);
    }

}
